/**
 * 
 */
package cn.ivicar.passport.controller;

import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.inject.Inject;

import cn.com.carsmart.exception.BadRequestException;
import cn.com.carsmart.exception.CarsmartException;
import cn.com.carsmart.exception.InternalErrorException;
import cn.com.carsmart.ws.model.Customer;
import cn.com.carsmart.ws.model.ValidateCode;
import cn.ivicar.passport.controller.utils.CaptchaTypeEnum;
import cn.ivicar.passport.controller.utils.PassportUtil;
import cn.ivicar.passport.service.PassportService;

/**
 * @author liurunbin 2017年5月16日
 */
public class PassportController {

	private static transient final Logger LOGGER = LoggerFactory.getLogger(PassportController.class);

	@Inject
	private PassportService passportService;
	@Inject
	private CaptchaController captchaController;

	/**
	 * 用户注册验证码
	 * mobile手机号 captcha验证码 password密码
	 */
	public Customer register(String mobile, String captcha, String password) throws CarsmartException {
		if (StringUtils.isBlank(mobile)) {
			throw new BadRequestException("400", "请输入手机号");
		}

		if (!PassportUtil.validateMobile(mobile)) {
			throw new BadRequestException("400", "手机号格式不正确");
		}

		if (passportService.getByMobile(mobile) != null) {
			String message = String.format("手机号[%s]已被占用.", mobile);
			LOGGER.info(message);
			throw new BadRequestException("400", message);
		}

		if (StringUtils.isBlank(captcha)) {
			throw new BadRequestException("400", "请先获取手机验证码");
		}

		if (StringUtils.isBlank(password)) {
			throw new BadRequestException("400", "请输入密码");
		}

		ValidateCode example = new ValidateCode();
		example.setValidateCode(captcha);
		example.setMobile(mobile);

		ValidateCode code = captchaController.checkCaptcha(mobile, captcha, CaptchaTypeEnum.REGISTER.getValue());

		Customer customer = new Customer();
		customer.setMobile(mobile);
		//密码加密
		customer.setPassword(PassportUtil.doSalt(password));
		try {
			passportService.insert(customer);
		} catch (CarsmartException e) {
			LOGGER.warn(String.format("用户[mobile=%s]注册失败", mobile), e);
			throw new BadRequestException("400", "注册失败");
		} catch (Exception e) {
			LOGGER.error(String.format("用户[mobile=%s]注册失败", mobile), e);
			throw new InternalErrorException("500", "注册失败");
		}
		// TODO:是否考虑并发注册场景

		captchaController.finishCaptcha(code);

		return customer;

	}

	/**
	 * 鉴权
	 */
	public Customer oAuthByMobile(String mobile, String password) throws CarsmartException {

		if (StringUtils.isBlank(mobile)) {
			throw new BadRequestException("400", "请输入手机号");
		}

		if (!PassportUtil.validateMobile(mobile)) {
			throw new BadRequestException("400", "手机号格式不正确");
		}

		if (StringUtils.isBlank(password)) {
			throw new BadRequestException("400", "请输入密码");
		}

		Customer customer = passportService.getByMobile(mobile);

		if (customer == null) {
			LOGGER.info(String.format("手机号[%s]未注册", mobile));
			throw new BadRequestException("400", "请先注册");
		}

		if (!customer.getPassword().equalsIgnoreCase(PassportUtil.doSalt(password))) {
			LOGGER.info(String.format("账号[%s]登录密码错误", mobile));
			throw new BadRequestException("400", "登录密码错误");
		}

		return customer;
	}

	/**
	 * 修改密码
	 */
	public boolean modifyPassword(Long customerId, String oldPwd, String newPwd) throws CarsmartException {
		if (customerId == null) {
			LOGGER.info("用户ID不能为空");
			throw new BadRequestException("400", "用户ID不能为空");
		}

		if (StringUtils.isBlank(oldPwd)) {
			throw new BadRequestException("400", "请输入原始密码！");
		}
		if (StringUtils.isBlank(newPwd)) {
			throw new BadRequestException("400", "请输入新密码！");
		}
		if (oldPwd.equals(newPwd)) {
			throw new BadRequestException("400", "原密码与新密码不能相同！");
		}

		Customer customer = this.passportService.get(customerId);

		if (customer == null) {
			LOGGER.info(String.format("指定的用户[%s]不存在", customerId));
			throw new BadRequestException("400", "指定用户不存在");
		}

		if (!customer.getPassword().equalsIgnoreCase(PassportUtil.doSalt(oldPwd))) {
			LOGGER.info(String.format("用户[%s]旧密码不正确, ", customer.getMobile()));
			throw new BadRequestException("400", "旧密码不正确");
		}

		Customer update = new Customer();
		update.setId(customerId);
		update.setPassword(PassportUtil.doSalt(newPwd));

		try {
			this.updateSelective(update);
		} catch (CarsmartException e) {
			LOGGER.warn(String.format("用户[customerId=%s]修改密码失败", customerId), e);
			throw new BadRequestException("400", "修改密码失败");
		} catch (Exception e) {
			LOGGER.error(String.format("用户[customerId=%s]修改密码失败", customerId), e);
			throw new InternalErrorException("500", "修改密码失败");
		}
		return true;
	}

	/**
	 * 重置密码
	 */
	public boolean resetPasswordByCode(String mobile, String newPwd, String captcha) throws CarsmartException {

		ValidateCode code = captchaController.checkCaptcha(mobile, captcha, CaptchaTypeEnum.RESTPASSWORD.getValue());

		if (StringUtils.isBlank(newPwd)) {
			throw new BadRequestException("400", "请输入新密码！");
		}

		Customer update = new Customer();
		update.setId(code.getCustomerId());
		update.setPassword(PassportUtil.doSalt(newPwd));

		try {
			this.updateSelective(update);
		} catch (CarsmartException e) {
			LOGGER.warn(String.format("用户[customerId=%s]重置密码失败", code.getCustomerId()), e);
			throw new BadRequestException("400", "重置密码失败");
		} catch (Exception e) {
			LOGGER.error(String.format("用户[customerId=%s]修改密码失败", code.getCustomerId()), e);
			throw new InternalErrorException("500", "重置密码失败");
		}
		captchaController.finishCaptcha(code);
		return true;
	}

	/**
	 * 修改手机号
	 */
	public boolean modifyMobile(String newMobile, String captcha) throws CarsmartException {

		if (StringUtils.isBlank(newMobile)) {
			throw new BadRequestException("400", "请输入新手机号");
		}

		if (!PassportUtil.validateMobile(newMobile)) {
			throw new BadRequestException("400", "手机号格式不正确");
		}

		if (passportService.getByMobile(newMobile) != null) {
			String message = String.format("手机号[%s]已被占用.", newMobile);
			LOGGER.info(message);
			throw new BadRequestException("400", message);
		}

		ValidateCode code = captchaController.checkCaptcha(newMobile, captcha,
				CaptchaTypeEnum.REPLACEMOBILE.getValue());

		Customer update = new Customer();
		update.setId(code.getCustomerId());
		update.setMobile(newMobile);

		try {
			this.updateSelective(update);
		} catch (CarsmartException e) {
			LOGGER.warn(String.format("用户[customerId=%s]修改手机号失败", code.getCustomerId()), e);
			throw new BadRequestException("400", "修改手机号失败");
		} catch (Exception e) {
			LOGGER.error(String.format("用户[customerId=%s]修改手机号失败", code.getCustomerId()), e);
			throw new InternalErrorException("500", "修改手机号失败");
		}
		captchaController.finishCaptcha(code);
		return true;

	}

	public boolean validateMobile(String mobile) {

		return PassportUtil.validateMobile(mobile);
	}

	public boolean mobileExist(String mobile) throws CarsmartException {

		boolean exist = false;
		if (StringUtils.isBlank(mobile)) {
			throw new BadRequestException("400", "请输入手机号");
		}

		if (!PassportUtil.validateMobile(mobile)) {
			throw new BadRequestException("400", "手机号格式不正确");
		}

		if (passportService.getByMobile(mobile) != null) {
			exist = true;
		}
		return exist;
	}

	public Customer get(Long customerId) {

		return this.passportService.get(customerId);
	}

	public int updateSelective(Customer update) throws CarsmartException {
		int result = this.passportService.updateSelective(update);
		return result;
	}

	public Customer getByMobile(String mobile) {
		return this.passportService.getByMobile(mobile);

	}

	public List<Customer> get(List<Long> cidList) {
		return this.passportService.get(cidList);
	}

}
